const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const db = require('./db/conn')

const ACCESS_TOKEN_SECRET = process.env.ACCESS_TOKEN_SECRET || 'dev_access_secret'
const REFRESH_TOKEN_SECRET = process.env.REFRESH_TOKEN_SECRET || 'dev_refresh_secret'
const ACCESS_TOKEN_EXPIRES_IN = process.env.ACCESS_TOKEN_EXPIRES_IN || '15m'
const REFRESH_TOKEN_EXPIRES_IN = process.env.REFRESH_TOKEN_EXPIRES_IN || '7d'

function signAccessToken(user) {
  return jwt.sign({ user_id: user.user_id, username: user.username }, ACCESS_TOKEN_SECRET, {
    expiresIn: ACCESS_TOKEN_EXPIRES_IN,
  })
}

function signRefreshToken(user) {
  return jwt.sign({ user_id: user.user_id, username: user.username }, REFRESH_TOKEN_SECRET, {
    expiresIn: REFRESH_TOKEN_EXPIRES_IN,
  })
}

router.post('/login', (req, res) => {
  const { username, password } = req.body || {}
  if (!username || !password) {
    return res.status(400).json({ message: '用户名或密码不能为空' })
  }
  const sql = 'SELECT * FROM user_info WHERE username = ? AND is_deleted = 0 AND status = 1 LIMIT 1'
  db.query(sql, [username], async (err, results) => {
    if (err) return res.status(500).json({ message: '数据库错误', error: err.message })
    if (!results || results.length === 0) return res.status(401).json({ message: '用户名或密码错误' })
    const user = results[0]
    console.log(user,'user...');
    console.log( user.password_hash);
    const ok = await bcrypt.compare(password, user.password_hash)
    console.log(ok,'ok....');
    if (!ok) return res.status(401).json({ message: '用户名或密码错误' })

    const accessToken = signAccessToken(user)
    const refreshToken = signRefreshToken(user)

    // 设置 httpOnly 刷新令牌 Cookie
    res.cookie('refresh_token', refreshToken, {
      httpOnly: true,
      secure: false,
      sameSite: 'lax',
      maxAge: 7 * 24 * 60 * 60 * 1000,
      path: '/auth',
    })

    // 更新登录信息
    const updateSql = 'UPDATE user_info SET last_login_time = NOW(), last_login_ip = ? WHERE user_id = ?'
    db.query(updateSql, [req.ip, user.user_id], () => {})

    return res.json({
      accessToken,
      user: {
        user_id: user.user_id,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        email: user.email,
      },
    })
  })
})

router.post('/refresh', (req, res) => {
  const token = req.cookies?.refresh_token
  if (!token) return res.status(401).json({ message: '未提供刷新令牌' })
  try {
    const payload = jwt.verify(token, REFRESH_TOKEN_SECRET)
    const accessToken = jwt.sign({ user_id: payload.user_id, username: payload.username }, ACCESS_TOKEN_SECRET, {
      expiresIn: ACCESS_TOKEN_EXPIRES_IN,
    })
    return res.json({ accessToken })
  } catch (err) {
    return res.status(401).json({ message: '刷新令牌无效或已过期' })
  }
})

router.post('/logout', (req, res) => {
  res.clearCookie('refresh_token', { path: '/auth' })
  return res.json({ message: '已退出登录' })
})

module.exports = router